export class WebSocketUtil {
  constructor(url) {
    this.url = url;
    this.socket = null;
    this.messageHandlers = [];
    this.errorHandlers = [];
    this.closeHandlers = [];
    this.openHandlers = [];
  }

  connect(userName) {
    if (this.socket) {
      this.disconnect();
    }

    const fullUrl = `${this.url}/${userName}`;
    this.socket = new WebSocket(fullUrl);

    this.socket.onopen = (event) => {
      this.openHandlers.forEach(handler => handler(event));
    };

    this.socket.onmessage = (event) => {
      this.messageHandlers.forEach(handler => handler(event.data));
    };

    this.socket.onerror = (event) => {
      this.errorHandlers.forEach(handler => handler(event));
    };

    this.socket.onclose = (event) => {
      this.closeHandlers.forEach(handler => handler(event));
    };
  }

  disconnect() {
    if (this.socket) {
      this.socket.close();
      this.socket = null;
    }
  }

  sendMessage(message) {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(message);
    }
  }

  addMessageHandler(handler) {
    this.messageHandlers.push(handler);
  }

  addErrorHandler(handler) {
    this.errorHandlers.push(handler);
  }

  addCloseHandler(handler) {
    this.closeHandlers.push(handler);
  }

  addOpenHandler(handler) {
    this.openHandlers.push(handler);
  }

  removeMessageHandler(handler) {
    this.messageHandlers = this.messageHandlers.filter(h => h !== handler);
  }

  removeErrorHandler(handler) {
    this.errorHandlers = this.errorHandlers.filter(h => h !== handler);
  }

  removeCloseHandler(handler) {
    this.closeHandlers = this.closeHandlers.filter(h => h !== handler);
  }

  removeOpenHandler(handler) {
    this.openHandlers = this.openHandlers.filter(h => h !== handler);
  }
}